import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication


class HandleEmail:
    def __init__(self, smtp_server, smtp_port, sender_email, sender_password):
        self.smtp_server = smtp_server
        self.smtp_port = smtp_port
        self.sender_email = sender_email
        self.sender_password = sender_password

    def send_email(self, receiver_email, subject, body, attachment_path=None, attachment_name=None,attachment_type='pdf'):
        """
        发送包含附件的电子邮件。

        参数：
        - receiver_email: 收件人邮箱地址
        - subject: 邮件主题
        - body: 邮件正文文本
        - attachment_path: 附件文件路径（如果不需要附件则可以为None）
        - attachment_name: 附件显示名称（如果提供attachment_path，则必须提供此项）
        - attachment_type: 附件类型，默认为'pdf'

        返回值：发送成功返回True，失败返回False
        """
        msg = MIMEMultipart()
        msg['From'] = self.sender_email
        msg['To'] = receiver_email
        msg['Subject'] = subject

        # 添加邮件正文
        msg.attach(MIMEText(body, 'plain'))

        # 如果提供了附件路径，则添加附件
        if attachment_path is not None:
            with open(attachment_path, 'rb') as f:
                report_attachment = MIMEApplication(f.read(), _subtype=attachment_type)
                report_attachment.add_header('Content-Disposition', 'attachment', filename=attachment_name)
                msg.attach(report_attachment)

        try:
            server = smtplib.SMTP(self.smtp_server, self.smtp_port)
            server.starttls()  # 如果SMTP服务器需要加密连接
            server.login(self.sender_email, self.sender_password)
            text = msg.as_string()
            server.sendmail(self.sender_email, receiver_email, text)
            server.quit()
            return True
        except Exception as e:
            print(f"发送邮件时发生错误: {e}")
            return False

# 使用方式
# sender = EmailSender("smtp.example.com", 587, "your_email@example.com", "your_email_password")
# result = sender.send_email(
#     "recipient_email@example.com",
#     '自动化测试报告',
#     '这是自动化测试报告，请查阅附件。',
#     'report_path',  # 附件路径
#     "test_report.pdf"  # 附件显示名称
# )
